﻿/****************************************
 *  copyright (c) 2008 leo shen
 *  
 *  all rights reserved         
 * 
 *  e-mail : syl.lucky@gmail.com
 * *************************************/

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using DotUpdater.Core.Versions;

namespace DotUpdater.Core.VersionGeters
{
    public class FilesConfigVersionGeter : IVersionGeter
    {
        XmlDocument doc;

        public FilesConfigVersionGeter(string filesConfigUrl)
        {
            doc = new XmlDocument();
        
           doc.Load(filesConfigUrl);           
        }

        #region IVersionGeter Members

        public DotUpdater.Core.Versions.IVersion GetVersion()
        {
            string strVersion = doc.GetElementsByTagName("application")[0].Attributes["version"].Value;
            System.Version ver = new Version(strVersion);
            return new ProgramVersion(ver);
        }

        public App_Folder GetAppFolderAndFiles()
        {
            App_Folder parentfolder = new App_Folder("app");
            XmlNode parentNode = doc.GetElementsByTagName("application")[0];
            generateFolderAndFiles(parentfolder, parentNode, string.Empty);
            return parentfolder;
        }

        void generateFolderAndFiles(App_Folder parentFolder, XmlNode parentNode, string preName)
        {
            foreach (XmlNode node in parentNode.ChildNodes)
            {
                if (node.Name.Equals("folder"))
                {
                    App_Folder folder = new App_Folder(preName + node.Attributes["name"].Value);
                    parentFolder.SubFolders.Add(folder);
                    generateFolderAndFiles(folder, node, folder.Name + @"\");
                }
                if (node.Name.Equals("file"))
                {
                    IVersion ver = null;
                    if (node.Attributes["version"] != null)
                        ver = new ProgramVersion(new Version(node.Attributes["version"].Value));
                    if (node.Attributes["lastModifiedTime"] != null)
                        ver = new LastModifiedVersion(DateTime.Parse(node.Attributes["lastModifiedTime"].Value));

                    App_File file = new App_File(preName + node.Attributes["name"].Value, ver);

                    if (node.Attributes["updateMode"] != null)
                    {
                        file.UpdateMode = (UpdateMode)Enum.Parse(typeof(UpdateMode), node.Attributes["updateMode"].Value);
                    }
                    parentFolder.Files.Add(file);
                }
            }
        }

        #endregion
    }
}
